package com.codedef.mapper;

import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.codedef.entity.ReservationRecord;
import com.codedef.entity.ReservationRecordVo;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;
import org.apache.ibatis.annotations.Update;

import java.util.Date;
import java.util.List;

@Mapper
public interface ReservationRecordMapper extends BaseMapper<ReservationRecord> {

    /**
     * 更新一个预约记录的状态
     */
    @Update("UPDATE reservation_record SET reservation_state = #{state} WHERE id = #{id} ")
    int updateReservationStateById(@Param("id") Integer id, @Param("state") Integer state);


    /**
     * 查询 某个人 某个座位 当前可以签到的预约 (15分)
     */
    @Select("SELECT * FROM reservation_record WHERE user_id = #{userId} AND seat_id = #{seatId} AND ( " +
            "NOW() BETWEEN DATE_SUB(reservation_record.start_time, INTERVAL 15 MINUTE) AND DATE_ADD(reservation_record.start_time, INTERVAL 15 MINUTE) ) ORDER BY start_time DESC LIMIT 1")
    ReservationRecord selectCanSignInReservationRecord(@Param("userId") Integer userId, @Param("seatId") Integer seatId);


    /**
     * 查询某个人的预约列表
     */
    @Select("SELECT reservation_record.id, reservation_record.user_id, reservation_record.seat_id, reservation_record.date, reservation_record.start_time, reservation_record.end_time, reservation_record.entry_time, reservation_record.reservation_state, floor.`name` AS floor_name, classroom.`name` AS classroom_name, seat.abbreviation AS seat_abbreviation " +
            "FROM floor, classroom, seat, reservation_record  WHERE floor.id = classroom.floor_id AND classroom.id = seat.classroom_id AND seat.id = reservation_record.seat_id " +
            "AND reservation_record.user_id = #{userId} ORDER BY reservation_record.start_time DESC ")
    List<ReservationRecordVo> selectReservationListByUserId(@Param("userId") Integer userId);

    /**
     * 获取一个座位某天的预约列表
     */
    @Select("SELECT * FROM reservation_record WHERE date = #{date} AND seat_id = #{seatId} AND reservation_state > 0 ")
    List<ReservationRecord> selectReservationListByDateAndSeatId(@Param("date") String date, @Param("seatId") Integer seatId);

    /**
     * 该用户这个时间段是否已存在预约
     */
    @Select("SELECT COUNT(*) FROM reservation_record WHERE user_id = 1 " +
            "AND ( #{dateA} BETWEEN start_time AND end_time " +
            "OR #{dateB} BETWEEN start_time AND end_time " +
            "OR #{dateA} < start_time AND #{dateB} > end_time ) AND reservation_state > 0 ")
    int selectUserReservationCountByTimePeriod(@Param("dateA") Date timeA, @Param("dateB") Date timeB);
}
